package com.cskaoyan.realm;

import com.cskaoyan.service.auth.AuthService;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: project-market
 * @description: 权限验证域
 * @author: Weiwei Liu
 * @create: 2021-12-01 15:13
 **/
@Component
public class CustomRealm extends AuthorizingRealm {


    @Autowired
    AuthService authService;

    /**
     * 先认证，username和password，入门凭证
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();
        String password = new String(token.getPassword());

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, this.getName());

        return simpleAuthenticationInfo;
    }


    /**
     * 把所有的钥匙都找出来
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 获取权限表
        String username = (String) principalCollection.getPrimaryPrincipal();

        // 通过username查询出所有的permission权限，先查admin表，查出ids，再查permission表
        List permissions = authService.queryPermissionByUsername(username);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }


}
